import React, { PureComponent } from 'react';
import { Form, Row, Col, Input, Button, Icon, Select,DatePicker } from 'antd';
import styles from './index.less';
import moment from 'moment';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
// @Form.create()
class PateoSearchForm extends PureComponent {
  state = {
    expandForm: false,
  };
  // 查询
  handleSearch = (e) => {
    e.preventDefault();
    const { dispatch, form, fetchUrl, payloadUrl, saveFormValues ,dateFormatList} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      for (let para in fieldsValue) {
        if ((fieldsValue[para] !== 0 && !fieldsValue[para]) || !fieldsValue[para].toString().trim()) {
          fieldsValue[para] = undefined
        }
      }

      // 使用时间段以rangeTime来接收，会进行拼接
      if (fieldsValue.rangeTime) {
        fieldsValue.rangeTime = `${moment(fieldsValue.rangeTime[0]).format('YYYY-MM-DD')},${moment(fieldsValue.rangeTime[1]).format('YYYY-MM-DD')}`;
      }
      //dateFormatList:是用来格式化时间的
      if (dateFormatList) {
        dateFormatList.map(title => fieldsValue[title]?
          (fieldsValue[title]=moment(fieldsValue[title]).format('YYYY-MM-DD HH:mm:ss')): (fieldsValue[title]=undefined));
      }

      /*
      * saveFormValues:子组件向父组件传递表单的数据
      * 和 dateFormatList 的顺序不可颠倒。
      * */
      if (saveFormValues) saveFormValues(fieldsValue);

      dispatch({
        type: fetchUrl,
        payload: payloadUrl ? Object.assign(payloadUrl, fieldsValue) : fieldsValue,
      });
    });
  };
  handleFormReset = () => {
    const { form, dispatch, fetchUrl, payloadUrl, handleFormReset } = this.props;
    form.resetFields();
    if (handleFormReset) {
      handleFormReset();
    }
    dispatch({
      type: fetchUrl,
      payload: payloadUrl || {},
    });
  };
  renderForm() {
    const { form: { getFieldDecorator }, searchItems } = this.props;
    const loopFormItems = data => data.map((item, i) => {
      if (!this.state.expandForm && i > 1) {
        return null;
      }
      const dateFormat = 'YYYY-MM-DD HH:mm:ss';
      const { title, key, type, max = Infinity } = item;
      switch (type) {
        case 'input': {
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem
                key={key}
                label={title}
              >
                {getFieldDecorator(key)(
                  <Input placeholder="请输入" autoComplete='off' allowClear maxLength={max}/>
                )}
              </FormItem>
            </Col>
          );
        }
        case 'select': {
          let optionsDiv;
          const { selectOptions,keyValue,} = item;
          if (selectOptions !== undefined) {
            const loopOptions = options => options.map((ite) => {
              if(keyValue){
                return<Option key={ite[keyValue[0]]} value={ite[keyValue[0]]}>{ite[keyValue[1]]}</Option>
              }else {
                return  <Option key={ite.value} value={ite.value}>{ite.label}</Option>;
              }
            });
            optionsDiv = loopOptions(selectOptions);
          }
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem key={key} label={title}>
                {getFieldDecorator(key)(
                  <Select
                    placeholder="请选择"
                    showSearch
                    allowClear
                  >
                    {optionsDiv}
                  </Select>
                )}
              </FormItem>
            </Col>
          );
        }
        case 'datePicker': {
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem key={key} label={title}>
                {getFieldDecorator(key)(
                <DatePicker
                  showTime
                  format={dateFormat}
                  showToday
                />
              )}
            </FormItem>
            </Col>
          );
        }
        // 时间段选择框
        case 'dateRange': {
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem
                key={key}
                label={title}
              >
                {getFieldDecorator(key)(
                  <RangePicker
                    showTime
                    style={{ width: '100%' }}
                    format="YYYY-MM-DD"
                  />
                )}
              </FormItem>
            </Col>
          );
        }
        //这个是用来调整格式的
        case 'blank':{
          return(
            <Col md={8} sm={24} key={key}>
              <FormItem key={key}>
              </FormItem>
            </Col>
          );
        }
        default: {
        }
      }
    });
    let nodeformItems;
    if (this.props.searchItems !== undefined) {
      nodeformItems = loopFormItems(searchItems);
    }
    return nodeformItems;
  }
  render() {
    const { searchItems = [],isExpand,searchSpan = 8} = this.props;
    const { expandForm } = this.state;
    const offset =
    isExpand ?
    (searchItems.length <= 2
      ? 16 - (searchItems.length % 3) * 8
      : expandForm
      ? 16 - (searchItems.length % 3) * 8
      : 0):16 - (searchItems.length % 3) * 8;
    return (
      <div className={styles.tableListForm}>
        <Form onSubmit={this.handleSearch} layout="inline">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            {this.renderForm()}
            <Col span={searchSpan} offset={offset}>
              <span className={this.state.expandForm ? styles.expendButtons : styles.submitButtons}>
                <Button type="primary" htmlType="submit">查询</Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
                {
                  this.props.searchItems.length > 2 ? (
                    <a
                      style={{ marginLeft: 8 }}
                      onClick={() => this.setState({ expandForm: !this.state.expandForm })}
                    >
                      {!this.state.expandForm ? <span>展开 <Icon type="down" /></span> : <span>收起 <Icon type="up" /></span>}
                    </a>
                  ) : null
                }
              </span>
            </Col>
          </Row>
        </Form>
      </div>
    );
  }
}

export default PateoSearchForm;
